#!/usr/bin/env python
# -*- coding=utf-8 -*-

import sys, os, math

def insert_in_file(dest, org, match, to_ins):
    fd_o = open(org, 'r')
    fd_d = open(dest, 'w')
    line_o = fd_o.readline()
    while line_o != '' and line_o != match:
        fd_d.write(line_o)
        line_o = fd_o.readline()
    for elem in to_ins:
        fd_d.write(elem)
    line_o = fd_o.readline()
    while line_o != '':
        fd_d.write(line_o)
        line_o = fd_o.readline()
    fd_o.close()
    fd_d.close()

def get_max_filenames_lenght(files):
    max = 0
    i = 0
    while i < len(files):
        if max < len(files[i]):
            max = len(files[i])
        i += 1
    return max

#def get_tab(filename, imax):
#    return ord('\t') * (((max + 7 - max % 8) - len(filename)) / 8)
    

def prepare_for_replace(files):
    max = get_max_filenames_lenght(files)
    max = max + 8 - max % 8
    i = 1
#    files[0] = "SRCS\t=\t" + files[0] + str(get_tab(files[0], max)) + " \\\n"
    files[0] = "SRCS\t=\t" + files[0] + " \\\n"
    while i < len(files) - 1:
#        files[i] = "\t\t" + files[i] + str(get_tab(files[i], max)) + " \\\n"
        files[i] = "\t\t" + files[i] + " \\\n"
        i = i + 1
    files[i] = "\t\t" + files[i] + '\n'

def list_files(folder):
    os.chdir(folder)
    files = []
    try:
        files = os.listdir(folder)
    except:
        return []
    for file in files:
        if (os.path.isdir(file)):
            files.extend([file+'/'+elem for elem in os.listdir(file)])
    return files

def keep_source_file(files):
    i = 0
    while i < len(files):
        if files[i][-2:] != '.c' or files[i][files[i].rfind('/') + 1] == '.':
            files.remove(files[i])
        else:
            i += 1
    return files

def main(patron, folder):
    files = list_files(folder)
    if len(files) == 0:
        print("folder is empty")
        quit()
    files = keep_source_file(files)
    files.sort()
    prepare_for_replace(files)
    insert_in_file('Makefile', patron, '@SOURCE-FILES@\n', files)

def print_usage():
    print("""Usage: MakeMakefile patron [folder]')
    Le fichier patron est un Makefile contenant la ligne "@SOURCE-FILES@"')
    qui sera remplacée par la liste des fichiers sources du dossier et ')
    des sous dossiers""")

if __name__ == '__main__':
    patron = ''
    folder = ''
    if (len(sys.argv) < 2 or len(sys.argv) > 4):
        print_usage()
        quit()
    if (len(sys.argv) == 3):
        folder = sys.argv[2]
    else:
        folder = '.'
    patron = sys.argv[1]
    main(patron, folder)
